package com.tg.app.activity.device.list;

import static android.app.Activity.RESULT_OK;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Consumer;
import androidx.core.view.GravityCompat;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.BuildConfig;
import com.appbase.custom.base.AuthCloseBean;
import com.appbase.custom.base.ServiceBought;
import com.appbase.custom.config.ApiUrl;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.PullLoadMore;
import com.demo.view.RecyclerViewOnScroll;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.core.backend.service.http.ClientObserver;
import com.tange.core.cloud.message.CloudMessage;
import com.tange.core.cloud.message.LocalPushConfigure;
import com.tange.core.cloud.message.PushSwitch;
import com.tange.core.cloud.message.RemotePushConfigure;
import com.tange.core.data.structure.Resp;
import com.tange.core.data.structure.Ret;
import com.tange.core.device.manage.DeviceInfoBasic;
import com.tange.core.device.manage.DeviceInfoQuery;
import com.tange.core.device.manage.DeviceOnlineStatus;
import com.tange.core.device.manage.DeviceThumbnail;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.share.ShareCodeManager;
import com.tange.module.socket.SocketIoConstants;
import com.tange.module.socket.SocketIoManager;
import com.tg.app.HomeWatcherReceiver;
import com.tg.app.MultiVersionHelper;
import com.tg.app.R;
import com.tg.app.activity.base.DeviceListBaseActivity;
import com.tg.app.activity.device.Buy4GServiceReminderActivity;
import com.tg.app.activity.device.NoDeviceActivity;
import com.tg.app.activity.device.add.AddFragmentTabActivity;
import com.tg.app.activity.device.add.ScanQrcodeActivity;
import com.tg.app.activity.device.doorlock.DoorLockLaunchHelper;
import com.tg.app.bean.FirmwareUpgrade;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.HomeKeyHelper;
import com.tg.app.helper.ServiceInfoHelper;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tg.app.service.UpgradeService;
import com.tg.app.socket.SocketIoService;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.view.MsgCenterToast;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tg.appcommon.helper.LogoutDialogHelper;
import com.tg.data.bean.DeviceItem;
import com.tg.data.helper.DeviceTypeStorage;
import com.tg.data.http.entity.DeviceServiceStatusBean;
import com.tg.data.http.entity.PushEventBean;
import com.tg.network.socket.http.TGHttp;
import com.widget.MarqueeAlertView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import io.objectbox.Box;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class DeviceListFragment extends DeviceListBaseFragment {
    public static final String TAG = "DeviceListFragmentTAG";
    public static final String PRE_REQUESTNOTIFICATION = "tg_notification";
    private static final int DEVICE_LIMIT = 10;
    private static final int UPGRADE = 3;
    private MyHandler handler;

    public static final String EXT_NOTIFICATION_UUID = "ext_notification_uuid";//
    public static final String ACTION_UPDATE_LIST = "action_update_list";

    private String notificationUUID = "";//推送传递过来的设备ID,如果不为空 说明是点击了通知栏的消息
    private DeviceBroadCastReceiver mReceiver;
    private boolean hasDeviceBroadCastReceiverRegister = false;

    public static final int CODE_NOT_LOGON = 0x0010;
    private final HomeKeyHelper mHomeKeyHelper = new HomeKeyHelper();
    private PullLoadMore pullLoadMore;

    /**
     * 标识本次打开页面，是否来源于消息通知的点击
     */
    private boolean comeFromNotification = false;

    private static final String FILTER_CLICK_TAG = "DeviceListFilter";
    // 过滤1s内的重复点击
    private static final int FILTER_CLICK_DURATION = 1000;
    private long lastItemClickTime = 0;


    private boolean firstRequestDone = false;
    private MarqueeAlertView marqueeAlertView;

    public static DeviceListFragment newInstance(boolean showTopBar, Bundle bundle) {
        TGLog.i(TAG, "[newInstance] bundle = " + bundle);
        DeviceListFragment fragment = new DeviceListFragment();
        Bundle args = new Bundle();
        if (bundle != null) {
            args.putAll(bundle);
        }
        args.putBoolean(PARAM_SHOW_TOP_BAR, showTopBar);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = super.onCreateView(inflater, container, savedInstanceState);
        onCreateViewInternal();
        return v;
    }

    private void onCreateViewInternal() {

        Intent intent = new Intent();
        Bundle bundle = getArguments();
        intent.putExtras(bundle);
        TGLog.i(TAG, "[onCreateViewInternal] bundle = " + bundle);
        getIntentData(intent);

        handler = new MyHandler(this);
        startSocketIoService();
        registerDeviceBroadCastReceiver();

        CameraHub.getInstance().setEnableLocalApConnect(false);
        MultiVersionHelper.finishLoginActivity();
        TGGlobalConfigHelper.getInstance().getAddDeviceVersionFromServer(null);
        initLoadMore();

        DeviceAddSoundConstants.downloadAllAudio(getActivity());

        marqueeAlertView = findViewById(R.id.alert_view);
    }


    @Override
    protected void onSearchTextChanged() {
        if (pullLoadMore != null) {
            pullLoadMore.setHasMore(true);
        }
    }


    private void initLoadMore() {
        pullLoadMore = new PullLoadMore(recyclerView,swipeRefreshLayout);
        recyclerView.addOnScrollListener(new RecyclerViewOnScroll(pullLoadMore));
        pullLoadMore.setOnLoadMoreListener(() -> {
            if (deviceCount > 0 && deviceCount <= deviceList.size()) {
                return;
            }
            devicePage++;
            getCameraList();
        });


    }

    public void getIntentData(Intent intent) {
        TGLog.i(TAG, "getIntentData: intent = " + intent);
        if (intent != null) {
            TGLog.i(TAG, "getIntentData: intent.getExtra = " + intent.getExtras());
        }
        getHmsData(intent);
        notificationUUID = intent.getStringExtra(EXT_NOTIFICATION_UUID);
        TGLog.i(TAG, "onCreate notificationUUID " + notificationUUID);
        long addNewDeviceId = intent.getLongExtra(AddFragmentTabActivity.EXT_DEVICE_ADD_QRCODE_SUCCEDD_ID, 0);
        TGLog.i(TAG, "onCreate addNewDeviceId " + addNewDeviceId);
        if (addNewDeviceId > 0) {
            String type = intent.getStringExtra(ApiUrl.DEVICE_TYPE);
            String uuid = intent.getStringExtra(ApiUrl.DEVICE_UUID);
            simAddSucceededDialog(addNewDeviceId, type, uuid);
        }
    }

    private void registerDeviceBroadCastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(SocketIoConstants.NOTIFY_ADD_DEVICE);
        filter.addAction(SocketIoConstants.NOTIFY_UNBIND_DEVICE);
        filter.addAction(SocketIoConstants.NOTIFY_DEVICE_STATUS);
        filter.addAction(NoDeviceActivity.ACTION_DEVICE_SHARE);

        mReceiver = new DeviceBroadCastReceiver();
        getActivity().registerReceiver(mReceiver, filter);
        hasDeviceBroadCastReceiverRegister = true;
    }

    private void startSocketIoService() {
        try {
            Intent serviceIntent = new Intent(getActivity(), SocketIoConstants.class);
            getActivity().startService(serviceIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private final HomeWatcherReceiver.HomeKeyHelperListener mHomeKeyHelperListener = () -> {
        TGLog.i(TAG, "[HomeWatcherReceiver] home key down");

    };

    @Override
    public void onStop() {
        super.onStop();
        mHomeKeyHelper.unregisterHomeKeyReceiver(getActivity());
        TGLog.i(TAG, "onStop");
    }

    private void getHmsData(Intent intent) {
        comeFromNotification = false;
        if (null != intent) {
            TGLog.i(TAG, "getHmsData: intent = " + intent);
            Bundle bundle = intent.getExtras();
            TGLog.i(TAG, "getHmsData: bundle = " + bundle);
            if (bundle != null) {
                JSONObject jsonObject = new JSONObject();
                Set<String> keys = bundle.keySet();
                for (String key : keys) {
                    TGLog.i(TAG, "getHmsData: found bundle key = " + key);
                    jsonObject.put(key, bundle.get(key));
                }
                String message_type_google= jsonObject.getString("message_type_google");
                if (!TextUtils.isEmpty(message_type_google)){
                    jsonObject.put("message_type",message_type_google);
                }
                String extraMap = JSONObject.toJSONString(jsonObject);
                TGLog.i(TAG, "getHmsData: extraMap = " + extraMap);
                PushEventBean eventBean = JSONObject.parseObject(extraMap, PushEventBean.class);
                TGLog.i(TAG, "getHmsData: eventBean = " + eventBean);


                ActivityHelper.gotoDeviceListPage(getActivity());
//                if (eventBean != null && !TextUtils.isEmpty(eventBean.message_type)) {
//                    DeviceItem deviceItem = null;
//                    for (DeviceItem item : deviceList) {
//                        if (TextUtils.equals(item.uuid, eventBean.uuid)) {
//                            deviceItem = item;
//                            break;
//                        }
//                    }
//                    TGLog.i(TAG, "getHmsData: deviceItem = " + deviceItem);
//                    comeFromNotification = true;
//                    TangeMessageReceiver.openNotificationActivity(getActivity(), eventBean, deviceItem, true, extraMap);
//
//                } else {
//                    TGLog.i(TAG, "getHmsData: PushEventBean is empty !");
//                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        TGLog.i(TAG, "onResume: ");

        //AppUpgradeManager.checkPendingInstallFileIfNeeded();

        mHomeKeyHelper.registerHomeKeyReceiver(getActivity(), mHomeKeyHelperListener);
        TGLog.d(DeviceListFragment.class.getSimpleName() + "onResume");
        handler.sendEmptyMessage(UPGRADE);
        openPushDevice();

        if (!comeFromNotification) {
            DoorLockLaunchHelper.checkIfExistNewCall(getActivity());
        } else {
            TGLog.i(TAG, "onResume: come from notification !");
        }

        // 每次恢复前台，都重新启动长连接服务
        if (firstRequestDone) {
            TGLog.i(SocketIoConstants.TAG + TAG, "onResume:  launch socket io service in 2 seconds");
            int userId = PreferenceUtil.getInt(getActivity(), CommonConstants.PRE_USER_ID);
            String text = safetyGetResources().getString(R.string.app_is_under_stand_by);
            String subText = safetyGetResources().getString(R.string.app_is_under_stand_by_sub_title);
            handler.postDelayed(() -> SocketIoManager.launchService(getActivity(), userId, R.mipmap.ic_launcher_round, text, subText), 2000);
        } else {
            TGLog.i(SocketIoConstants.TAG + TAG, "onResume: not launch socket io service");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        comeFromNotification = false;
        TGLog.i(TAG, "onPause: ");
    }

    @Override
    protected void buildAdpater() {
        isListDisplay = PreferenceUtil.getBoolean(getActivity(), CommonConstants.PRE_DEVICE_LIST_SHOW);

        // 首页多样式支持需求：不展示顶部栏的时候（即多Tab），只能以列表模式展示
        if (!shouldShowTopBar) {
            isListDisplay = true;
        }

        listDisplay(isListDisplay);
    }

    private void requireDeviceThumbnail(List<String> list) {
        DeviceInfoQuery.INSTANCE.requireThumbnail(list, new Consumer<Resp<Map<String, DeviceThumbnail>>>() {
            @Override
            public void accept(Resp<Map<String, DeviceThumbnail>> mapResp) {
                if (mapResp != null && mapResp.getSuccess() && mapResp.getData() != null) {
                    TGLog.i(TAG, "[requireDeviceThumbnail][onNext] success");
                    Map<String, DeviceThumbnail> data = mapResp.getData();
                    for (DeviceItem device : deviceList) {
                        DeviceThumbnail deviceThumbnail = data.get(device.uuid);
                        if (deviceThumbnail != null) {
                            device.setDeviceThumbnail(deviceThumbnail);
                        }
                    }
                    onRequestDevicesSuccess();
                    onRequestDevicesFinished();
                    updateUI();

                } else {
                    TGLog.i(TAG, "[requireDeviceThumbnail][onNext] failed");
                }

            }
        });
    }

    private void requireDeviceOnlineStatus(List<DeviceInfoBasic> deviceInfoBasicList) {
        List<String> list = new ArrayList<>();
        TGLog.i(TAG, "deviceInfoBasic.size = " + deviceList.size());
        TGLog.i(TAG, "deviceInfoBasicList.size = " + deviceInfoBasicList.size());
        for (int i = 0; i < deviceInfoBasicList.size(); i++) {
            String uuid = deviceInfoBasicList.get(i).getDeviceId();
            list.add(uuid);
            TGLog.i(TAG, "deviceInfoBasic.uuid = " + uuid);
            TGLog.i(TAG, "deviceInfoBasic.getDeviceAttributes = " + deviceInfoBasicList.get(i).getDeviceAttributes());
            TGLog.i(TAG, "deviceInfoBasic.getDeviceAbilities = " + deviceInfoBasicList.get(i).getDeviceAbilities());
            boolean find = false;

            if (devicePage == 1){
                for (DeviceItem device : deviceList) {
                    if (TextUtils.equals(device.uuid, uuid)) {
                        find = true;
                        device.setDeviceInfoBasic(deviceInfoBasicList.get(i));
                        break;
                    }
                }
            }

            if (!find){
                deviceList.add(i, new DeviceItem(deviceInfoBasicList.get(i)));
            }
        }
        if (devicePage == 1){
            if (deviceList.size() > 0){
                for (int i = deviceList.size() - 1; i > -1; i--) {
                    if (!list.contains(deviceList.get(i).uuid)){
                        deviceList.remove(i);
                    }
                }
            }
        }

        DeviceInfoQuery.INSTANCE.requireOnlineStatus(list, mapResp -> {
            if (mapResp != null && mapResp.getSuccess() && mapResp.getData() != null) {
                TGLog.i(TAG, "[requireDeviceOnlineStatus][onNext] success");
                Map<String, DeviceOnlineStatus> data = mapResp.getData();
                for (DeviceItem device : deviceList) {
                    DeviceOnlineStatus deviceOnlineStatus = data.get(device.uuid);
                    device.setDeviceOnlineStatus(deviceOnlineStatus);
                }
                requireDeviceThumbnail(list);
                updateUI();
            } else {
                String error = mapResp == null ? "no-detail" : mapResp.getMessage();
                TGToast.showToast("requireDeviceOnlineStatus Failed to request devices: " + error);
                TGLog.d(TAG, "requireDeviceOnlineStatus Failed to request devices: " + error);
                onRequestDevicesSuccess();
                onRequestDevicesFinished();
            }
        });

//        QueryDeviceInfo.queryDeviceInfo(list, deviceListResp -> {
//            List<DeviceListResp.Device> devices = deviceListResp.getList();
//            TGLog.i(TAG, "CloudServiceActivity: " + devices);
//            if (devices != null){
//                TGLog.i(TAG, "CloudServiceActivity: size =" + devices.size());
//            }
//            for (DeviceListResp.Device device : devices){
//                TGLog.i(TAG, "CloudServiceActivity: " + device.getUuid() + ", " + device.getId() + "," + device.getTimezone());
//                for (DeviceItem deviceItem : deviceList){
//                    if (StringUtils.equals(device.getUuid(), deviceItem.uuid)){
//                        deviceItem.id = device.getId();
//                        break;
//                    }
//                }
//            }
//        });
        String uuids =  StringUtils.join(list, ",");
        ServiceInfoHelper.getServiceInfo(uuids, new ServiceInfoHelper.ServiceInfoListener<HashMap<String, DeviceServiceStatusBean>>() {
            @Override
            public void onSuccess(HashMap<String, DeviceServiceStatusBean> resp) {
                TGLog.i(TAG, "[query][onSuccess] resp = " + resp);
                if (resp != null){
                    for (DeviceItem deviceItem : deviceList){
                        DeviceServiceStatusBean deviceServiceStatusBean = resp.get(deviceItem.uuid);
                        if (deviceServiceStatusBean != null){
                            deviceItem.server_data = deviceServiceStatusBean.storage;
                            deviceItem.sim_server_data = deviceServiceStatusBean.sim;
                            deviceItem.car_server_data = deviceServiceStatusBean.car;
                            deviceItem.ai_server_data = deviceServiceStatusBean.ai;
                            deviceItem.foreignServiceHook = deviceServiceStatusBean.foreign_service_hook;
                            if (deviceItem.server_bought == null){
                                deviceItem.server_bought = new ServiceBought();
                            }
                            deviceItem.server_bought.ai_server = deviceServiceStatusBean.bought.ai? 1 : 0;
                            deviceItem.server_bought.car_server = deviceServiceStatusBean.bought.car? 1 : 0;
                            deviceItem.server_bought.sim_server = deviceServiceStatusBean.bought.sim? 1 : 0;
                            deviceItem.server_bought.server = deviceServiceStatusBean.bought.storage? 1 : 0;
                        }
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorInfo) {
                String msg = "errorCode = " + errorCode + " , errorInfo = " + errorInfo;
                TGLog.i(TAG, "[query][onResponseError] " + msg);
            }
        });

        updatePushingSwitch();

    }

    private void updatePushingSwitch(){
        for (DeviceItem deviceItem : deviceList) {
            if (!deviceItem.isShare()) {
                updatePushingSwitch(deviceItem);
            }
        }
    }

    private void updatePushingSwitch(final DeviceItem deviceItem){
        TGThreadPool.executeDelay(new Runnable() {
            @Override
            public void run() {
                CloudMessage.INSTANCE.queryPushingSwitch(deviceItem.uuid, new Consumer<Resp<RemotePushConfigure>>() {
                    @Override
                    public void accept(Resp<RemotePushConfigure> resp) {
                        final String uuid = deviceItem.uuid;
                        if (resp != null && resp.getSuccess() && resp.getData() != null) {
                            RemotePushConfigure remotePushConfigure = resp.getData();
                            TGLog.d(TAG, "queryPushingSwitch: " + remotePushConfigure);
                            TGLog.d(TAG, "queryPushingSwitch.interval: " + remotePushConfigure.getInterval());
                            TGLog.d(TAG, "queryPushingSwitch.getEnable: " + remotePushConfigure.getEnable());
                            TGLog.d(TAG, "queryPushingSwitch.getUndisturbed: " + remotePushConfigure.getUndisturbed());
                            TGLog.d(TAG, "queryPushingSwitch.getSwitcher: " + remotePushConfigure.getSwitcher());
                            List<PushSwitch> pushSwitchList = remotePushConfigure.getSwitcher();
                            List<String> list = new ArrayList<>();
                            if (pushSwitchList != null) {
                                for (PushSwitch pushSwitch : pushSwitchList) {
                                    String categoryLabel = pushSwitch.getCategoryLabel();
                                    TGLog.d(TAG, "queryPushingSwitch.categoryLabel: " + categoryLabel);
                                    list.add(categoryLabel);
                                }
                            }

                            LocalPushConfigure localPushConfigure = new LocalPushConfigure();
                            localPushConfigure.setEnable(true);
                            localPushConfigure.setInterval(remotePushConfigure.getInterval());
                            localPushConfigure.setUndisturbed(remotePushConfigure.getUndisturbed());
                            localPushConfigure.setTagWhichNeedToPush(list);

                            CloudMessage.INSTANCE.updatePushingSwitch(uuid, localPushConfigure, new Consumer<Ret>() {
                                @Override
                                public void accept(Ret ret) {
                                    TGLog.d(TAG, "updatePushingSwitch: " + ret);
                                }
                            });
                        }
                    }
                });
            }
        }, 500);

    }


    public void getCameraList() {
        int offset = (devicePage == 1) ? 0 : deviceList.size();
        Log.i(TAG, "getCameraList: ...devicePage:" + devicePage + ", offset:" + offset);
        DeviceInfoQuery.INSTANCE.requireBasic(offset, DEVICE_LIMIT, "", deviceInfoPaginationResp -> {
            if (deviceInfoPaginationResp != null && deviceInfoPaginationResp.getSuccess()
                    && deviceInfoPaginationResp.getData() != null) {
                TGLog.i(TAG, "[getCameraList][onNext] success");
                deviceCount = deviceInfoPaginationResp.getData().getTotal();

                List<DeviceInfoBasic> deviceInfoBasicList = deviceInfoPaginationResp.getData().getList();
                if (deviceInfoBasicList != null && deviceInfoBasicList.size() > 0){
                    requireDeviceOnlineStatus(deviceInfoBasicList);
                }else{
                    if (devicePage == 1){
                        deviceList.clear();
                        onRequestDevicesSuccess();
                        onRequestDevicesFinished();
                    }
                }
                updateUI();
                TGLog.i(TAG, "deviceCount = " + deviceCount);
            } else {
                String error = deviceInfoPaginationResp == null ? "no-detail" : deviceInfoPaginationResp.getMessage();
                int code = deviceInfoPaginationResp == null ? 0 : deviceInfoPaginationResp.getCode();
                TGLog.d(TAG, "Failed to request devices: " + error + ", code: " + code);
                onRequestDevicesFinished();
                if (401 == code){
                    LogoutDialogHelper.getInstance().showLogoutDialog(null);
                }

            }
        });
    }

    private void onRequestDevicesFinished() {
        swipeRefreshLayout.setRefreshing(false);
        pullLoadMore.setLoadMoreCompleted();
    }

    private void onRequestDevicesSuccess() {
        if (getActivity() == null) return;

        BizWiFiUtil.saveNetworkWifi();

        if (deviceList != null && deviceList.size() > 0) {
            TGLog.i(TAG, "items.size() =  " + deviceList.size());
            if (deviceList.size()<DEVICE_LIMIT){
                pullLoadMore.setHasMore(false);
            }


            // 将所有设备保存起来，后续用于比对信息
            DeviceTypeStorage.saveAllDevice(getActivity(), deviceList);

            List<String> uuids = new ArrayList<>();

            for (DeviceItem deviceItem : deviceList) {
                uuids.add(deviceItem.uuid);
                TGLog.trace(TAG);
                TGLog.i(TAG, "deviceItem.size =  " + deviceList.size());
                TGLog.i(TAG, "deviceItem.device_type " + deviceItem.device_type + " devicename = " + deviceItem.name + ", preconnect = " + deviceItem.getPreconnect() + ", uuid = " + deviceItem.uuid);
                TGLog.i(TAG, "deviceItem.attrs =  " + deviceItem.attrs);
                TGLog.i(TAG, "deviceItem.timezone =  " + deviceItem.timezone);
                TGLog.i(TAG, "deviceItem.isShare =  " + deviceItem.isShare());
                TGLog.i(TAG, "deviceItem.abilities =  " + deviceItem.abilities + ", deviceItem.ai_abilities = " + deviceItem.deviceBasicResp.getAiAbilities());
                TGLog.i(TAG, "deviceItem.is_online =  " + deviceItem.is_online);
                TGLog.i(TAG, "deviceItem.image_path =  " + deviceItem.image_path);

                // 保存信息用于后续比对，
                // 这两句不要删除，否则告警消息等地方逻辑将会异常！
                DeviceTypeStorage.saveDevice(getActivity(), deviceItem);
                DeviceTypeStorage.saveDeviceRotation(getActivity(), deviceItem, DeviceHelper.getRotation(deviceItem));

            }

            firstRequestDone = true;
            int userId = PreferenceUtil.getInt(getActivity(), CommonConstants.PRE_USER_ID);
            String text = safetyGetResources().getString(R.string.app_is_under_stand_by);
            String subText = safetyGetResources().getString(R.string.app_is_under_stand_by_sub_title);
            SocketIoManager.launchService(getActivity(), userId, R.drawable.ic_home_launcher_round, text, subText);
        }else {
            pullLoadMore.setHasMore(false);
            DeviceTypeStorage.clearAllDevice(getActivity());
        }
        updateUI();

        recognizeShareCode();
    }


    private void recognizeShareCode() {
        if (isHostActivityValid()) {
            ShareCodeManager.getInstance().recognize(getActivity(), DeviceTypeStorage.readAllDevices(getActivity()), true, false, new Runnable() {
                @Override
                public void run() {
                    if (isHostActivityValid()) {
                        swipeRefreshLayout.setRefreshing(true);
                        getCameraList();
                    }
                }
            });
        }
    }

    private boolean isHostActivityValid() {
        if (getActivity() != null) {
            final Activity activity = getActivity();
            return activity != null && !activity.isFinishing() && !activity.isDestroyed();
        }

        return false;
    }


    @Override
    public void updateUI() {
        super.updateUI();
        // 来自通知栏  跳转到通知栏的设备去
        if (deviceList.size() > 0) {
            openPushDevice();
        } else {
            isListDisplay = PreferenceUtil.getBoolean(getActivity(), CommonConstants.PRE_DEVICE_LIST_SHOW);
            emptyDisplay(isListDisplay);
        }
    }

    private void openPushDevice() {
        if (deviceList.size() > 0) {
            if (!TextUtils.isEmpty(notificationUUID)) {
                for (DeviceItem item : deviceList) {
                    if (TextUtils.equals(item.uuid, notificationUUID)) {
                        openDevice(item, DeviceListBaseActivity.PUSH_TARGET_LIVE);
                        notificationUUID = "";
                        break;
                    }
                }
            }
        }
    }

    public void onNewIntent(Intent intent) {
        TGLog.i(TAG, "[onNewIntent] intent = " + intent);
        getIntentData(intent);
    }

    public void onActivityRestart() {
        TGLog.i(TAG, "onActivityRestart: ");
        getCameraList();
    }

    public void onTabReShow() {
        TGLog.i(TAG, "onTabReShow: ");
        getCameraList();
    }

    @Override
    public boolean onBackKeyClicked() {
        uploadLog("account_menu");
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else {
            getActivity().finish();
        }

        return true;
    }

    @Override
    public void onItemClick(int position, int type) {
        if (System.currentTimeMillis() - lastItemClickTime < FILTER_CLICK_DURATION) {
            Log.i(FILTER_CLICK_TAG, "onItemClick: click filter ! ");
            return;
        }
        Log.i(FILTER_CLICK_TAG, "onItemClick: real-click");
        lastItemClickTime = System.currentTimeMillis();


        DeviceItem item = deviceList.get(position);
        if (type != DeviceListBaseActivity.OPEN_UPGRADE) {
            String action = "list";
            if (!isListDisplay) {
                action = "card";
            }
            uploadLog(action + "live");
            DeviceHelper.openCameraDevice(getActivity(), type, item);
        } else if (item.is_online != DeviceStateConstants.DEVICE_ONLINE) {
            MsgCenterToast.show(TGApplicationBase.getApplication(), R.string.tips_device_offline);
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        TGLog.i(TAG, "onActivityResult");
        if (resultCode == RESULT_OK) {
            if (data != null) {
                long device = data.getLongExtra(CommonConstants.EXT_DEVICE_ID, 0);
                if (device > 0) {
                    showAuthAlertClose(device);
                }
            }
        }
    }

    @Override
    public void onViewClick() {
        if (BuildConfig.device_global_addByQrCodeScanning) {
            Intent  toAddChoose = new Intent(getActivity(), ScanQrcodeActivity.class);
            startActivity(toAddChoose);
        } else {
            ActivityHelper.gotoAddDeviceHomePage(getActivity());
        }

    }


    static class MyHandler extends Handler {
        private final WeakReference<DeviceListFragment> mActivity;

        private MyHandler(DeviceListFragment activity) {
            mActivity = new WeakReference<>(activity);
        }

        private Activity getActivity() {
            if (mActivity != null && mActivity.get() != null && mActivity.get().getActivity() != null) {
                return mActivity.get().getActivity();
            }
            return null;
        }

        @SuppressLint("NotifyDataSetChanged")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CODE_NOT_LOGON:
                    TGLog.d(TGLog.TAG, "msg ==========" + msg);
                    if (getActivity() != null) {
                        MultiVersionHelper.startLoginActivity(getActivity());
                        getActivity().finish();
                    }
                    break;
                case UPGRADE://用于假更新
                    if (getActivity() == null) {
                        return;
                    }
                    Box<FirmwareUpgrade> box = ObjectBoxUtil.getFirmwareUpgrade();
                    if (box != null && box.count() > 0 && mActivity.get() != null) {
                        Intent upgradeIntent = new Intent(getActivity(), UpgradeService.class);
                        UpgradeService.enqueueWork(getActivity(), upgradeIntent);
                        // 假更新 180秒会显示更新失败
                        Message message = Message.obtain();

                        if (msg.arg1 > 60) {
                            msg.arg1 = 0;
//                            mActivity.get().getCameraList();
                        }
                        message.arg1 = msg.arg1+1;
                        message.what = UPGRADE;
                        sendMessageDelayed(message, 1000);
                        mActivity.get().mAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        TGLog.i(TAG, "onDestroy");
        super.onDestroy();
        if (getActivity() != null && hasDeviceBroadCastReceiverRegister) {
            getActivity().unregisterReceiver(mReceiver);
        }

        if (marqueeAlertView != null) {
            marqueeAlertView.dismissDialogIfNeeded();
        }
    }


    private void showAuthAlertClose(long device) {
        final TGAlertDialog tgAlertDialog = new TGAlertDialog(getActivity()).builder();
        tgAlertDialog.setMessage(R.string.sim_auth_alert_close).setPositiveButton(R.string.sim_auth_alert_close_sure, view -> {
            HashMap<String, String> hash = new HashMap<>();
            hash.put("device_id", String.valueOf(device));
            // 每天检查一次；强制更新，启动一次检查一次
            TGHttp.getInstance().appAuthClose(hash)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ClientObserver<AuthCloseBean>() {
                        @Override
                        protected void onSuccess(AuthCloseBean content) {
                            getCameraList();
                        }
                    });
        }).setNegativeButton(R.string.cancel, v -> {
        });

        tgAlertDialog.show();
    }

    private class DeviceBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            switch (action) {
                case SocketIoConstants.NOTIFY_ADD_DEVICE:
                case NoDeviceActivity.ACTION_DEVICE_SHARE:
                    TGLog.e(SocketIoService.TAG, "receive add");
                    getCameraList();
                    break;
                case SocketIoConstants.NOTIFY_UNBIND_DEVICE:
                    Log.e(SocketIoService.TAG, "receive unbind");
                    getCameraList();
                    break;
                case SocketIoConstants.NOTIFY_DEVICE_STATUS:
                case ACTION_UPDATE_LIST:
                    TGLog.d("receive devices status : " + action);
                    getCameraList();
                    break;
            }
        }
    }

    private void simAddSucceededDialog(final long id, String type, String uuid) {
        Buy4GServiceReminderActivity.launch(getActivity(), id, type, uuid);
    }

}
